#!/usr/bin/python
# -*- coding: utf-8 -*-
# coding:utf-8
import urllib2
import constant.constant_value as constant

def write_file(image_name,image_url):
    image_path = ""
    try:
        split_list = str(image_url).split('/')
        domain = split_list[0]+"//"+split_list[2]
        # 创建请求对象
        request = urllib2.Request(image_url)
        request.add_header('Referer',domain)
        request.add_header("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; MyIE9; BTRS123646; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)")
        request.add_header("Host", split_list[2])
        data =  urllib2.urlopen(request,data=None,timeout=3).read()

        path = constant.image_base_path+image_name
        f = file(path,"wb")
        f.write(data)
        f.close()
        image_path = path
        print image_url,u"图片下载成功！"
    except Exception as err:
        print image_url,u"图片下载失败",err;
        image_path = "";
    return image_name,image_path

if __name__ == '__main__':
    print write_file(u"5570444df22e3.png","http://img1.tuliu.com//art/2015/06/04/5570444df22e3.png")
    pass